#!/bin/sh
#-
# Copyright (c) 2014 iXsystems, Inc., All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL Jordan Hubbard OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

. /etc/rc.subr

__DC_tc()
{
	local timeout=$1
	shift
	local args="$*"

	local i=0
	local ret=1
	local lf="$(mktemp /tmp/tmp.XXXXXX)"

	lockf -k -s -t 0 ${lf} ${args} &
	ret=$?
	lpid=$!

	if [ "${ret}" != "0" ]
	then
		return ${ret}
	fi

	ret=2
	while [ ${i} -lt ${timeout} ]
	do
		sleep 1

		if lockf -k -s -t 0 ${lf} /usr/bin/true
		then
			rm -f ${lf}
			ret=0
			break
		fi

		: $((i += 1))
	done

	kill $! >/dev/null 2>&1
	pid="$(ps -axwww|grep "$args"|grep -v grep|awk '{ print $1 }')"
	if [ -n "${pid}" ]
	then
		kill ${pid} >/dev/null 2>&1
	fi

	pid="$(ps -axwww|grep "$args"|grep -v grep|awk '{ print $1 }')"
	if [ -n "${pid}" ]
	then
		kill -9 ${pid} >/dev/null 2>&1
	fi

	wait ${lpid}
	ret=$?

	rm -f ${lf}
	return ${ret}
}

__do_DC_get()
{
	local prefix="${1}"
	local name="${2}"
	local var=\$$(printf "${prefix}${name}")
	local val=$(eval "echo ${var} 2>/dev/null")

	__unescape "${val}"
}

DC_get()
{
	local vars="${*}"
	local prefix="__dc_"

	for v in ${vars}
	do
		local var=\$$(printf "${v}")
		local val=$(eval "echo ${var} 2>/dev/null")

		if [ -n "${val}" ]
		then
			echo "${val}"
		else		
			__do_DC_get "${prefix}" "${v}" 2>/dev/null
		fi
	done
}

__do_DC_set()
{
	local prefix="${1}"
	local var="${2}"
	local val=$(__escape "${3}")
	local pair="${var}=${val}"

	eval "${prefix}${pair}"
}

DC_set()
{
	local var="${1}"
	local val="${2}"
	local prefix="__dc_"

	__do_DC_set "${prefix}" "${var}" "${val}" 2>/dev/null
}

DC_show_config()
{
	printf "DC Domain Config:\n"
	printf "+------------------------------------------------------+\n"
	printf "dc_realm:            %s\n" $(DC_get dc_realm)
	printf "dc_domain:           %s\n" $(DC_get dc_domain)
	printf "dc_role:             %s\n" $(DC_get dc_role)
	printf "dc_dns_backend:      %s\n" $(DC_get dc_dns_backend)
	printf "dc_dns_forwarder:    %s\n" $(DC_get dc_dns_forwarder)
	printf "dc_forest_level:     %s\n" $(DC_get dc_forest_level)
	printf "dc_passwd:           %s\n" $(DC_get dc_passwd)
	printf "+------------------------------------------------------+\n"
}

DC_log()
{
	local args="$*"

	local on="$(DC_get dc_verbose_logging)"
	if [ "${on}" = "1" ]
	then
		logger -t "DC" ${args} >/dev/null 2>&1
	fi
}

DC_load_database_values()
{
	local tmpfile="$(mktemp -q /var/tmp/.dcfoo.XXXXXX)"

	cat << __SQL__ | ${FREENAS_SQLITE_CMD} -line ${FREENAS_CONFIG} > ${tmpfile}
	SELECT
		dc_realm,
		dc_domain,
		dc_role,
		dc_dns_backend,
		dc_dns_forwarder,
		dc_forest_level,
		dc_passwd

	FROM
		services_domaincontroller

	ORDER BY
		-id

	LIMIT 1;
__SQL__

	exec 3<&0
	exec 0<"${tmpfile}"
	while read -r line
	do
		var=$(echo ${line}|cut -f1 -d=|xargs)
		val=$(echo ${line}|cut -f2- -d=|xargs)

		if [ "${var}" = "dc_passwd" ]; then
			DC_set "${var}" "$(/usr/local/bin/midclt call notifier.pwenc_decrypt ${val})"
		else
			DC_set "${var}" "${val}"
		fi
	done
	exec 0<&3
	rm "${tmpfile}"
}

DC_get_hostname()
{
	local hostname
	local domain
	local hostname_field

	if [ "$(ha_node)" = "B" ]; then
		hostname_field="gc_hostname_b"
	else
		hostname_field="gc_hostname"
	fi

	hostname="$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "
		SELECT ${hostname_field} FROM network_globalconfiguration")"
	domain="$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "
		SELECT gc_domain FROM network_globalconfiguration")"

	if [ -n "${hostname}" -a -n "${domain}" ]
	then
		hostname="${hostname}.${domain}"
	elif [ -z "${hostname}" ]
	then
		hostname="$(/bin/hostname)"
	fi

	echo "${hostname}"
}

DC_init()
{
	DC_load_database_values
	DC_set dc_hostname "$(DC_get_hostname)"

	return 0
}

domaincontroller_enabled()
{
	srv_enabled domaincontroller
}

domaincontroller_set()
{
	srv_set domaincontroller "${1}"
}
